/**
  
 *
 
 *
   
 */

package com.develop.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.develop.annotation.Login;
import com.develop.config.WxMaConfiguration;
import com.develop.form.LoginForm;
import com.develop.common.utils.R;
import com.develop.common.validator.ValidatorUtils;
import com.develop.entity.TokenEntity;
import com.develop.entity.UserEntity;
import com.develop.service.TokenService;
import com.develop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.Map;

/**
 * 登录接口
 *

 */
@RestController
@RequestMapping("/api")
@Api(tags="登录接口")
public class ApiLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        //用户登录
        Map<String, Object> map = userService.login(form);

        return R.ok(map);
    }
    /**
     * 登陆接口
     */
    @PostMapping("/cxcLogin")
    public R cxcLogin( String code,String appId ,String secret)  {
        if (StringUtils.isBlank(code)) {
            return R.error("请传code");
        }
        String xcxAppId = "wx523dc16cf654a5c1";
        String xcxSecret = "6c093144ed04ce086115a99259a3fd92";

        if(StringUtils.isNotEmpty(appId))
        {
            xcxAppId=appId;
        }
        if(StringUtils.isNotEmpty(secret))
        {
            xcxSecret=secret;
        }
        UserEntity user=null;
        String openid="";
        try {
            final WxMaService wxService = WxMaConfiguration.getMaService(xcxAppId,xcxSecret);


            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);

             openid=session.getOpenid();
            LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserEntity::getWxOpenid,openid);

             user=    userService.getOne(queryWrapper);
        }
        catch (Exception e)
        {
            //使用默认账号，测试用
            user=userService.getById(12);
        }




        if(null==user)
        {
            user=new UserEntity();
            user.setCreateTime(new Date());
            user.setWxOpenid(openid);
            user.setXcxAppId(xcxAppId);
            user.setXcxSecret(xcxSecret);
            userService.save(user);
        }
        else
        {
            user.setXcxAppId(xcxAppId);
            user.setXcxSecret(xcxSecret);
            userService.updateById(user);

        }



        TokenEntity tokenEntity = tokenService.createToken(user.getId());
            return R.ok().put("token",tokenEntity.getToken()).put("user",user);

    }
    @Login
    @PostMapping("logout")
    @ApiOperation("退出")
    public R logout(@ApiIgnore @RequestAttribute("userId") long userId){
        tokenService.expireToken(userId);
        return R.ok();
    }

}
